package cn.edu.ctbu.datajpa1.webapi;


import cn.edu.ctbu.datajpa1.core.PageUtils;
import cn.edu.ctbu.datajpa1.domain.Student;
import cn.edu.ctbu.datajpa1.service.StudentService;
import cn.edu.ctbu.datajpa1.utils.RUtil;
import cn.edu.ctbu.datajpa1.vo.R;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@RestController
@Slf4j

@RequestMapping("/webapi/student")
public class StudentRestController {

    @Autowired
    private StudentService studentService;


    /*
     * 读取的url:/webapi/student/list
     * @return
     * */
    /*@GetMapping("/list")
    public List<Student> getAll() {
        List<Student> students = studentService.findAll();

        return students;

    }*/

    /*
     * 分页读取全部内容
     * */
    @GetMapping("/getbypage")
    public PageUtils getByPage(@RequestParam(value = "page", defaultValue = "0") Integer page,
                               @RequestParam(value = "size", defaultValue = "10") Integer size,
                               @RequestParam(value = "name", defaultValue = "") String name) {
        //按id排倒序
        Sort sort = Sort.by(Sort.Direction.DESC, "id");

        Page<Student> studentPage;
        if (StringUtils.isEmpty(name)) {

            Pageable pageable = PageRequest.of(page, size, sort);
            studentPage = studentService.findAll(pageable);

        } else {
            Student student = new Student();
            student.setName(name);

            //全部模糊查询即 %{name}%
            Pageable pageable = PageRequest.of(0, 10, sort);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());

            Example<Student> example = Example.of(student, matcher);
            studentPage = studentService.findAll(example, pageable);
        }

        PageUtils pageUtils = new PageUtils(studentPage.getContent(), studentPage.getTotalElements());

        return pageUtils;


    }

    /*
     * 读取的url:/webapi/student/get/id
     * @return
     * */
    @GetMapping("/get/{id}")
    public Student get(@PathVariable Integer id) {
        Student students = studentService.getById(id);
        students.setPassword("");

        return students;

    }

    /*
     * 新增学生的方法. /webapi/student/insert
     *@param student
     * @return
     * */
    @PostMapping(value = "/insert")
    public int insert(@Valid Student student, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldError().getDefaultMessage();
            return -1;
        }
        studentService.insert(student);
        String myName = student.getName();
        return myName.indexOf(myName);
    }

    /*
     * 更新学生的方法. /webapi/student/update
     *@param student
     * @return
     * */
    @PutMapping("/update")
    public Student update(Student student) {
        //读取旧数据
        Student oldstudent = studentService.getById(student.getId());
        if (StringUtils.isEmpty(student.getPassword())) {
            //没有新密码那么就是旧密码
            student.setPassword(oldstudent.getPassword());
        }

        student = studentService.update(student);
        return student;
    }

    /*
     * 删除学生的方法. /webapi/student/delete  用路径的方式删除
     *@param student
     * @return
     * */
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Integer id) {

        studentService.delete(id);
    }

    /*
     * 按姓名查询 /webapi/student/find
     *@param student
     * @return
     * */
    @GetMapping("/find")
    @ResponseBody
    public List<Student> getStudentByName(String name) {
        List<Student> student1 = studentService.findAll();

        return student1;
    }

    /*@PostMapping(value = "/add")
    public int add(@Valid Student student, @NotNull BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return -1;
        }
        studentService.insert(student);

        String myName = student.getName();
        System.out.println(myName);
        if (myName != null)
            return 1;
        return 0;
    }*/



    @PostMapping("/add")
    public R add(@Valid Student student, @NotNull BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String errorMsg=bindingResult.getFieldError().getDefaultMessage();
            log.info("新增学生出错!{}",errorMsg);

            return RUtil.error(-10,errorMsg);
        }
        studentService.insert(student);

        return RUtil.success();
    }


    @GetMapping("/validateUser")
    public R validataSnoAndPassword(String sno,String password) throws Exception {
        return RUtil.success(studentService.validateSnoAndPassword(sno,password));
    }


    @GetMapping("/list")
    public R<Page<Student>> list(int pageIndex, int pageSize) {
        Pageable pageable = PageRequest.of(pageIndex, pageSize, Sort.by("id").descending());
        return RUtil.success(studentService.findAll(pageable));
    }


}